package com.ydlclass.interceptor;

import com.fasterxml.jackson.core.type.TypeReference;
import com.ydlclass.configuration.CustomObjectMapper;
import com.ydlclass.constant.Constants;
import com.ydlclass.core.RedisTemplate;
import com.ydlclass.entity.YdlLoginUser;
import org.springframework.http.ResponseEntity;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author rumaodi
 * @date 2022/11/5 16:44
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private CustomObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 设置一个白名单
        // List<String> whiteNames = List.of("/admin/login");
        // if(whiteNames.contains(request.getRequestURI())) return true;

        // 2. 如果不是白名单的请求,检测
        // 判断有没有Authorization这个请求头,拿到首部信息的Authorization的值
        ResponseEntity<String> res = ResponseEntity.status(401).body("Bad Credenti!");
        String token = request.getHeader(Constants.HEAD_AUTHORIZATION);
        if(token == null){
            response.setStatus(401);
            response.getWriter().write(objectMapper.writeValueAsString(res));
            return false;
        }

        // 3. 使用token去redis中查看,有没有对应的loginUser
        YdlLoginUser ydlLoginUser = redisTemplate.getObject(Constants.TOKEN_PREFIX + token, new TypeReference<>() {});
        if(ydlLoginUser == null){
            response.setStatus(401);
            response.getWriter().write(objectMapper.writeValueAsString(res));
            return false;
        }

        return true;
    }
}
